<?php


namespace app\task\cron\coupon;

use app\model\CouponConfig;
use app\model\CouponBrand;
use app\model\CouponProductChannel;
use app\model\Config;
use yunwuxin\cron\Task;

class TakeDownBySellPrice extends Task
{
    /**
     * 五分钟跑一次
     */
    protected function configure()
    {
        // 分 时 日 月 周
        $this->expression = '*/5 * * * *';
    }

    /**
     * 执行指令.
     */
    protected function handle()
    {
        echo '开始品牌权益检查销售价是否大于市场价开始' . PHP_EOL;
        $lockKey = 'coupon_product_channel_take_down_lock_key1';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢' . PHP_EOL;
            return true;
        }

        cache($lockKey, 1, 10*60);

        $config = new Config();
        $premiumRate = [];
        //查询总平台溢价
        /**
         * @var Config $platformPremiumRate
         * @var Config $agentPremiumRate
         */
        $platformPremiumRate = $config->getPlatformPremiumRate();
        if ($platformPremiumRate) {
            $premiumRate['platformPremiumRat'] = $platformPremiumRate->value;
        }
        //查询代理端统一溢价
        $agentPremiumRate = $config->getAgentPremiumRate();
        if ($agentPremiumRate) {
            $premiumRate['agentPremiumRate'] = $agentPremiumRate->value;
        }
        $i = 1;
        $params = [
            'list_rows'    => 10,
            'config_type'  => CouponConfig::CONFIG_TYPE_DLDG,
            'is_agent'     => 1,
            'premiumRate'  => $premiumRate
        ];
        do {
            $params['page'] = $i;
            $list = (new CouponBrand())->getDefaultTempList($params);
            $brands = $list['data'];
            //halt($brands);
            $totalTakeDownNum = 0;
            foreach ($brands as $brand) {
                //品牌下的产品信息
                $brandProductChannels = $brand['brandProductChannel'];
                foreach ($brandProductChannels as $brandProductChannel) {
                    //产品下架
                    if ($brandProductChannel['sale_price_text'] > $brandProductChannel['market_price']) {
                        /**
                         * @var CouponProductChannel $couponProductChannel
                         */
                        $couponProductChannel = CouponProductChannel::query()->where('id', $brandProductChannel['id'])->find();
                        $couponProductChannel->shelf_state = CouponProductChannel::SHELF_STATE_XZ;
                        $couponProductChannel->save();
                        $totalTakeDownNum++;
                    }
                    //todo 品牌不下架，没有产品，品牌不会显示
                }
            }
            $i++;
        } while ($list['total'] > 0 && $list['total'] > ($i-1)*$params['list_rows']);

        cache($lockKey, null);

        echo '开始品牌权益检查销售价是否大于市场价结束,总共下架产品数'. $totalTakeDownNum.PHP_EOL;
    }
}